/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.institution.service.impl;

import com.koron.common.bean.StaffBean;
import com.koron.institution.bean.LawCategory;
import com.koron.institution.mapper.LawCategoryMapper;
import com.koron.institution.mapper.LawMapper;
import com.koron.institution.service.api.LawCategoryService;
import com.koron.institution.uitls.BaseEntityUtil;
import com.koron.institution.uitls.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class LawCategoryServiceImpl implements LawCategoryService {

    private final static  Logger logger = LoggerFactory.getLogger(Logger.class);

    @Override
    public MessageBean<?> getCategoryList() {
        MessageBean<List> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), List.class);
        try (SessionFactory factory = new SessionFactory()) {
            LawCategoryMapper mapper = factory.getMapper(LawCategoryMapper.class);
            List<LawCategory> categoryList = mapper.getCategoryList();
            List<LawCategory> treeList = new ArrayList<>();
            if (categoryList != null && !categoryList.isEmpty()) {
                treeList = categoryList.stream().filter(category -> "root".equalsIgnoreCase(category.getPid())).collect(Collectors.toList());
                createTree(treeList, categoryList);
            }
            msg.setData(treeList);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    void createTree(List<LawCategory> treeList, List<LawCategory> list) {
        if (list == null || list.isEmpty() || treeList == null || treeList.isEmpty()) {
            return;
        }
        List<LawCategory> childList = null;
        for (LawCategory lawCategory : treeList) {
            childList = list.stream().filter(category -> lawCategory.getId().equals(category.getPid())).collect(Collectors.toList());
            createTree(childList, list);
            lawCategory.setChildList(childList);
        }
    }

    @Override
    public MessageBean<?> addCategory(LawCategory category, StaffBean user) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        try {
            LawCategoryMapper mapper = factory.getMapper(LawCategoryMapper.class);
            if (category == null) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(category.getCategoryName())) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY_NAME.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY_NAME.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(category.getPid())) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY_PID.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY_PID.getDescription());
                return msg;
            }
            //  校验是否已存在
            Integer cheak = mapper.cheak(category.getCategoryName(), category.getPid(), category.getId());
            if (cheak > 0) {
                msg.setCode(BusinessCode.CATEGORY_EXIST.getCode());
                msg.setDescription(BusinessCode.CATEGORY_EXIST.getDescription());
                return msg;
            }
            BaseEntityUtil.setAddBaseProperties(category, user);
            Integer value = mapper.insert(category);
            if (value <= 0) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("保存失败");
                return msg;
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<?> deleteCategory(String categoryId, StaffBean user) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        try {
            LawCategoryMapper lawCategoryMapper = factory.getMapper(LawCategoryMapper.class);
            LawMapper lawMapper = factory.getMapper(LawMapper.class);
            LawCategory lawCategory = lawCategoryMapper.selectByPrimaryKey(categoryId);
            if (null == lawCategory) {
                msg.setCode(BusinessCode.CATEGORY_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.CATEGORY_NOT_EXIST.getDescription());
                return msg;
            }
            //获取目录下的法规数据数量
            int count = lawMapper.countByCategoryId(categoryId);
            if (count > 0) {
                msg.setCode(BusinessCode.CATEGORY_EXIST_INSTITUTIONS.getCode());
                msg.setDescription(BusinessCode.CATEGORY_EXIST_INSTITUTIONS.getDescription());
                return msg;
            }
            //获取目录下子目录数量
            Integer categoryCount = lawCategoryMapper.getCategoryCount(categoryId);
            if (categoryCount > 0) {
                msg.setCode(BusinessCode.CATEGORY_EXIST_INSTITUTIONS.getCode());
                msg.setDescription(BusinessCode.CATEGORY_EXIST_INSTITUTIONS.getDescription());
                return msg;
            }
            Integer delete = lawCategoryMapper.deleteByPrimaryKey(categoryId);
            if (delete <= 0) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
                return msg;
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<?> updateCategory(LawCategory category, StaffBean user) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        try {
            LawCategoryMapper mapper = factory.getMapper(LawCategoryMapper.class);
            if (category == null) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(category.getId())) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY_ID.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY_ID.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(category.getCategoryName())) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY_NAME.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY_NAME.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(category.getPid())) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY_PID.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY_PID.getDescription());
                return msg;
            }
            LawCategory entity = mapper.selectByPrimaryKey(category.getId());
            if (entity == null) {
                msg.setCode(BusinessCode.CATEGORY_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.CATEGORY_NOT_EXIST.getDescription());
                return msg;
            }
            // 校验是否已存在
            Integer cheak = mapper.cheak(category.getCategoryName(), category.getPid(), category.getId());
            if (cheak > 0) {
                msg.setCode(BusinessCode.CATEGORY_EXIST.getCode());
                msg.setDescription(BusinessCode.CATEGORY_EXIST.getDescription());
                return msg;
            }
            BaseEntityUtil.setUpdateBaseProperties(category, user);
            Integer update = mapper.updateByPrimaryKeySelective(category);
            if (update <= 0) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("修改失败");
                return msg;
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }
}
